package cn.com.connected.config.DataSource;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import lombok.Getter;
import lombok.Setter;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;


@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
@MapperScan(basePackages = "cn.com.connected.mapper", sqlSessionTemplateRef = "sqlSessionTemplate")
@Getter
@Setter
public class DatacenterConfiguration {

    private String driverClassName;

    private String url;

    private String username;

    private String password;

    private int connectionTimeout;

    private int idleTimeout;

    private int maxLifetime;

    private int maximumPoolSize;

    /**
     * 配置dataSource，使用Hikari连接池
     */
    @Bean(name = "dataSource", destroyMethod = "close")
    @Primary
    public DataSource dataSource() {
        return new DatacenterDataSource().getHikariDataSource(driverClassName,url,username,password,connectionTimeout,idleTimeout,maxLifetime,maximumPoolSize);
    }

    @Bean(name = "sqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
//        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        Resource[] base = new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/**/*.xml");
        bean.setMapperLocations(base);

        bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);

        return bean.getObject();
    }

    @Bean(name = "dataSourceTransactionManager")
    @Primary
    public DataSourceTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "sqlSessionTemplate")
    @Primary
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
